<template>
  <div class="app-container">
    <!-- 查询条件表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 作物下拉框 -->
      <el-form-item label="作物名称" prop="cropName">
        <el-select
          v-model="queryParams.cropName"
          placeholder="请选择作物"
          clearable
          filterable
          style="width: 200px"
          @change="queryParams.phenologicalperiodname = null"
        >
          <el-option
            v-for="item in cropOptions"
            :key="item.cropid"
            :label="item.cropname"
            :value="item.cropname"
          />
        </el-select>
      </el-form-item>

      <!-- 物候期下拉框 -->
      <el-form-item label="物候期名称" prop="phenologicalperiodname">
        <el-select
          v-model="queryParams.phenologicalperiodname"
          placeholder="请选择物候期"
          clearable
          filterable
          style="width: 200px"
        >
          <el-option
            v-for="item in filteredPhenologicalperiodOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <!-- 时间选择 -->
      <el-form-item label="开始时间" prop="starttime">
        <el-date-picker
          clearable
          v-model="queryParams.starttime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endtime">
        <el-date-picker
          clearable
          v-model="queryParams.endtime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间"
        />
      </el-form-item>

      <!-- 查询/重置按钮 -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:phenologicalperiods:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:phenologicalperiods:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:phenologicalperiods:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:phenologicalperiods:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="phenologicalperiodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="物候期ID" align="center" prop="phenologicalperiodid" /> -->
      <el-table-column label="作物名称" align="center" prop="cropname" />
      <el-table-column label="物候期名称" align="center" prop="phenologicalperiodname" />
      <el-table-column label="开始时间" align="center" prop="starttime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.starttime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endtime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物候期特点" align="center" prop="characteristics" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:phenologicalperiods:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:phenologicalperiods:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="phenologicalperiodsRef" :model="form" :rules="rules" label-width="100px">
        <!-- 作物下拉框 -->
        <el-form-item label="作物名称" prop="cropid">
          <el-select v-model="form.cropid" placeholder="请选择作物" filterable>
            <el-option
              v-for="item in cropOptions"
              :key="item.cropid"
              :label="item.cropname"
              :value="item.cropid"
            />
          </el-select>
        </el-form-item>

        <!-- 物候期名称 -->
        <el-form-item label="物候期名称" prop="phenologicalperiodname">
          <el-input v-model="form.phenologicalperiodname" placeholder="请输入物候期名称" />
        </el-form-item>

        <!-- 时间 -->
        <el-form-item label="开始时间" prop="starttime">
          <el-date-picker clearable v-model="form.starttime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endtime">
          <el-date-picker clearable v-model="form.endtime" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间" />
        </el-form-item>

        <!-- 物候期特点 -->
        <el-form-item label="物候期特点" prop="characteristics">
          <el-input v-model="form.characteristics" type="textarea" placeholder="请输入内容" :rows="10"/>
        </el-form-item>

        <!-- 标准化生产指导信息 -->
        <el-divider content-position="center">标准化生产指导信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddPhenologicalguidance">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeletePhenologicalguidance">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="phenologicalguidanceList" :row-class-name="rowPhenologicalguidanceIndex" @selection-change="handlePhenologicalguidanceSelectionChange" ref="phenologicalguidance">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="指导名称" prop="guidancename" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.guidancename" placeholder="请输入指导名称" />
            </template>
          </el-table-column>
          <el-table-column label="指导周期" prop="guidanceperiod" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.guidanceperiod" placeholder="请输入指导周期" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, computed, getCurrentInstance } from "vue"
import { listPhenologicalperiods, getPhenologicalperiods, delPhenologicalperiods, addPhenologicalperiods, updatePhenologicalperiods } from "@/api/agriculture/xctl/phenologicalperiods"
import { listCrops } from "@/api/agriculture/xctl/crops"

const { proxy } = getCurrentInstance()
const phenologicalperiodsList = ref([])
const phenologicalguidanceList = ref([])
const cropOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedPhenologicalguidance = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const allPhenologicalperiods = ref([])
const allPhenologicalperiodsMap = ref({})

function buildPhenologicalperiodsMap() {
  const map = {}
  allPhenologicalperiods.value.forEach(item => {
    const cropName = item.cropname
    if (!map[cropName]) map[cropName] = []
    map[cropName].push(item.phenologicalperiodname)
  })
  allPhenologicalperiodsMap.value = map
}

function loadAllPhenologicalperiods() {
  listPhenologicalperiods({ pageNum: 1, pageSize: 9999 }).then(res => {
    allPhenologicalperiods.value = res.rows || []
    buildPhenologicalperiodsMap()
  })
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    cropid: null,
    cropName: null,
    phenologicalperiodname: null,
    starttime: null,
    endtime: null,
    characteristics: null
  },
  rules: {
    cropid: [{ required: true, message: "作物ID不能为空", trigger: "blur" }],
    phenologicalperiodname: [{ required: true, message: "物候期名称不能为空", trigger: "blur" }]
  }
})
const { queryParams, form, rules } = toRefs(data)

const filteredPhenologicalperiodOptions = computed(() => {
  const crop = queryParams.value.cropName
  if (!crop) return allPhenologicalperiods.value.map(item => item.phenologicalperiodname)
  return allPhenologicalperiodsMap.value[crop] || []
})

function getList() {
  loading.value = true
  listPhenologicalperiods(queryParams.value).then(res => {
    phenologicalperiodsList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

function loadCropOptions() {
  listCrops({ pageNum: 1, pageSize: 9999 }).then(res => {
    cropOptions.value = res.rows || []
  })
}

onMounted(() => {
  loadCropOptions()
  loadAllPhenologicalperiods()
  getList()
})

function handleQuery() { queryParams.value.pageNum = 1; getList() }
function resetQuery() { proxy.resetForm("queryRef"); handleQuery() }
function handleSelectionChange(selection) { ids.value = selection.map(i => i.phenologicalperiodid); single.value = selection.length != 1; multiple.value = !selection.length }
function handleAdd() { reset(); open.value = true; title.value = "添加作物物候期管理" }
function handleUpdate(row) {
  reset()
  const _id = row.phenologicalperiodid || ids.value
  getPhenologicalperiods(_id).then(res => {
    form.value = res.data
    phenologicalguidanceList.value = res.data.phenologicalguidanceList
    open.value = true
    title.value = "修改作物物候期管理"
  })
}
function submitForm() {
  proxy.$refs["phenologicalperiodsRef"].validate(valid => {
    if (valid) {
      form.value.phenologicalguidanceList = phenologicalguidanceList.value
      if (form.value.phenologicalperiodid != null) {
        updatePhenologicalperiods(form.value).then(() => { proxy.$modal.msgSuccess("修改成功"); open.value = false; getList() })
      } else {
        addPhenologicalperiods(form.value).then(() => { proxy.$modal.msgSuccess("新增成功"); open.value = false; getList() })
      }
    }
  })
}
function handleDelete(row) {
  const _ids = row.phenologicalperiodid || ids.value
  proxy.$modal.confirm(`是否确认删除作物物候期管理编号为"${_ids}"的数据项？`).then(() => delPhenologicalperiods(_ids)).then(() => { getList(); proxy.$modal.msgSuccess("删除成功") }).catch(()=>{})
}
function cancel() { open.value = false; reset() }
function reset() { form.value = { phenologicalperiodid:null, cropid:null, phenologicalperiodname:null, starttime:null, endtime:null, characteristics:null }; phenologicalguidanceList.value = []; proxy.resetForm("phenologicalperiodsRef") }
function rowPhenologicalguidanceIndex({ row, rowIndex }) { row.index = rowIndex + 1 }
function handleAddPhenologicalguidance() { phenologicalguidanceList.value.push({ guidancename: "", guidanceperiod: "", standardizedImplementation: "", imageUrl: "" }) }
function handleDeletePhenologicalguidance() {
  if (!checkedPhenologicalguidance.value.length) proxy.$modal.msgError("请先选择要删除的标准化生产指导信息数据")
  else phenologicalguidanceList.value = phenologicalguidanceList.value.filter(item => !checkedPhenologicalguidance.value.includes(item.index))
}
function handlePhenologicalguidanceSelectionChange(selection) { checkedPhenologicalguidance.value = selection.map(i => i.index) }
function handleExport() { proxy.download('system/phenologicalperiods/export', {...queryParams.value}, `phenologicalperiods_${Date.now()}.xlsx`) }
</script>
